package com.jielin.handling.controller.material;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jielin.handling.Annotation.MyPower;
import com.jielin.handling.bean.AppResult;
import com.jielin.handling.entity.material.*;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.service.material.MaterialFileService;
import com.jielin.handling.service.material.MaterialPackService;
import com.jielin.handling.service.material.MaterialTypeDocumentService;
import com.jielin.handling.service.material.MaterialTypeService;
import com.jielin.handling.util.ConstantUtil;
import com.jielin.handling.util.StringUtil;
import com.jielin.handling.util.VideoImageUtil;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author WR 卷宗信息管理（卷宗信息上传，打包）
 */
@CrossOrigin
@RestController
@RequestMapping("/material")
@MyPower(name = "卷宗信息管理（卷宗信息上传，打包）", type = 0, url = "/material")
@Validated
@Slf4j
public class MaterialController {
    @Autowired
    private MaterialFileService materialFileService;
    @Autowired
    private MaterialPackService materialPackService;
    @Autowired
    private MaterialTypeDocumentService materialTypeDocumentService;
    @Autowired
    private MaterialTypeService materialTypeService;

    /**
     * 根据案件编号,嫌疑人id,民警id,一级名称模糊查询对应的一级卷宗信息
     *
     * @param caseCode         警综案件编号
     * @param policeId         上传打包新增警员id
     * @param caseSuspectId    嫌疑人id
     * @param materialTypeName 一级类别名称
     * @return
     */
/*    @MyPower(name = "模糊查询一级卷宗信息", url = "/findMaterialByCaseCode")
    @RequestMapping(value = "/findMaterialByCaseCode")
    public AppResult findMaterialByCaseCode(String caseCode, String policeId, String caseSuspectId,
                                            String materialTypeName, @RequestParam(name = "isRetract", defaultValue = "0") int isRetract) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        List<MaterialType> list = materialTypeService.findMaterialByAllAndName(caseCode, policeId, caseSuspectId,
                materialTypeName, isRetract);

        data.put("value", list);
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setMsg("查询成功!");
        result.setData(data);
        return result;
    }*/

    /**
     * 根据一级目录id查询文件夹信息（根据文件夹名称模糊查询）
     *
     * @param materialtypeid 一级目录id
     * @param documentName   文件夹名称
     * @return
     */
    @MyPower(name = "根据一级目录id查询文件夹信息", url = "/findDocumentByMaterialTypeId")
    @RequestMapping(value = "/findDocumentByMaterialTypeId")
    public AppResult findDocumentByMaterialTypeId(String materialtypeid,
                                                  @RequestParam(value = "documentName", required = false) String documentName) {
        JSONObject data = new JSONObject();
        data.put("value", materialTypeDocumentService.findDocumentByMaterialTypeId(materialtypeid, documentName));
        return AppResult.builder().setCode(ResultEnum.SUCCESS.getCode()).setMsg(ResultEnum.SUCCESS.getMsg()).setData(data);
    }

    /**
     * 根据文件夹id查询文件信息（根据文件名称模糊查询）
     *
     * @param documentid 文件夹id
     * @param fileName   文件名称
     * @return
     */
    @MyPower(name = "根据文件夹id查询文件信息", url = "/findFileByDocumentId")
    @RequestMapping(value = "/findFileByDocumentId")
    public AppResult findFileByDocumentId(String documentid, String fileName) {
        JSONObject data = new JSONObject();
        List<MaterialFile> list = materialFileService.findFileByDocumentId(documentid, fileName);
        if (!ConstantUtil.XSKYRESTORAGE) {
            list.stream().forEach(item -> {
                item.setUrl(ConstantUtil.returnIp() + item.getUrl());
                item.setThumbnailpath(ConstantUtil.returnIp() + item.getThumbnailpath());
            });
        }
        data.put("value", list);
        return AppResult.builder().setCode(ResultEnum.SUCCESS.getCode()).setMsg(ResultEnum.SUCCESS.getMsg()).setData(data);
    }

    /**
     * 上传文件信息(新增三级文件) 更新二级文件夹总数加1
     *
     * @param files      文件
     * @param documentid 文件夹id
     * @param fileString Base64格式字符串
     * @return
     */
    @MyPower(name = "上传文件信息(新增三级文件) 更新二级文件夹总数加1", url = "/addFile")
    @RequestMapping(value = "/addFile")
    public AppResult addFile(@RequestParam(value = "file", required = false) MultipartFile[] files,
                             @NotNull(message = "传入的documentId为null，请传值")
                             @NotEmpty(message = "传入的documentId空字符串，请传值") String documentid, String fileString) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("..........addFile");
        if (ConstantUtil.XSKYRESTORAGE) {
            // 二级文件夹信息
            MaterialTypeDocument document = materialTypeDocumentService.findDocumentById(documentid);
            MaterialType mt;
            if (document == null) {
                data.put("value", "未查询到文件夹信息！");
                return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("添加警告！").setData(data);
            } else {
                // 一级目录信息
                mt = materialTypeService.findById(document.getMaterialtypeid());
            }

            if (materialFileService.addDossierFile(files, documentid, document, mt, fileString) > 0) {
                return AppResult.builder().setCode(ResultEnum.SUCCESS.getCode()).setMsg("文件上传成功！");
            } else {
                return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("文件上传失败！(可能原因：1.上传文件为空；2.xsky上传失败)");
            }
        } else {
            if (StringUtil.isEmpty(documentid)) {
                data.put("value", "请传入文件夹id！");
                result.setCode(ResultEnum.FAIL.getCode());
                result.setMsg("添加警告！");
                result.setData(data);
                return result;
            } else {
                MaterialTypeDocument document = materialTypeDocumentService.findDocumentById(documentid);// 二级文件夹信息
                MaterialType mt = new MaterialType();
                if (document == null) {
                    data.put("value", "未查询到文件夹信息！");
                    result.setCode(ResultEnum.FAIL.getCode());
                    result.setMsg("添加警告！");
                    result.setData(data);
                    return result;
                } else {
                    mt = materialTypeService.findById(document.getMaterialtypeid());// 一级目录信息
                }
                // 文件存放路径==》 案件名称-警员id-案件编号/嫌疑人姓名/一级目录名称/二级文件夹名称/
                String rootpath = mt.getCasename() + "-" + mt.getUploadpoliceid() + "-" + mt.getCasecode() + File.separator
                        + mt.getCaseSuspectName() + File.separator + mt.getMaterialtypename() + File.separator
                        + document.getDocumentname();
                try {
                    boolean isHaveFile = files != null && files.length > 0;
                    MultipartFile file = null;
                    if (isHaveFile) {
                        file = files[0];
                    }
                    if (file != null) {// 表单上传文件
                        String fileName = file.getOriginalFilename();// 文件原名称
                        // 自定义的文件名称
                        String trueFileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.lastIndexOf("."))
                                + System.currentTimeMillis();
                        // 获取文件类型
                        String fileType = fileName.substring(fileName.lastIndexOf("."));
                        // 设置存放图片文件的路径
                        String filedocpath = ConstantUtil.FILE_PATH + rootpath + File.separator;
                        String path = filedocpath + trueFileName + fileType;
                        File newFile = new File(filedocpath);
                        if (!newFile.exists()) {
                            newFile.mkdirs();
                        }
                        // 转存文件到指定的路径
                        // file.transferTo(newFile);//(放绝对路径)
                        byte[] bytes = file.getBytes();
                        BufferedOutputStream buffStream = new BufferedOutputStream(new FileOutputStream(new File(path)));// (放相对路径)
                        buffStream.write(bytes);
                        buffStream.close();

                        MaterialFile materialFile = new MaterialFile();
                        materialFile.setId(StringUtil.generatorUUID());
                        materialFile.setMaterialtypedocumentid(documentid);
                        materialFile.setFilename(trueFileName + fileType);
                        materialFile.setUrl(path);
                        materialFile.setFiletype(fileType);
                        if (fileType.matches(
                                "^(.jpg|.png|.JPG|.PNG|.jpeg|.JPEG|.gif|.GIF|.bmp|.BMP|.svg|.SVG|.ico|.ICO|.tif|.TIF)$")) {// 如果文件后缀是图片格式就生成缩略图
                            String thumbnailpath = ConstantUtil.FILE_PATH + rootpath + File.separator;
                            String truepath = thumbnailpath + trueFileName + "thumbnail" + fileType;
                            File newFile1 = new File(thumbnailpath);
                            if (!newFile1.exists()) {
                                newFile1.mkdirs();
                            }
                            // 生成缩略图
                            Thumbnails.of(path).size(200, 300).toFile(truepath);
                            // 设置缩略图路径
                            materialFile.setThumbnailpath(truepath);
                        } else if (fileType
                                .matches("^(.mp4|.MP4|.mov|.MOV|.AVI|.avi|.mkv|.MKV|.flv|.FLY|.rmvb|.RMVB|.wmv|.WMV)$")) {// 如果文件后缀是视频格式就生成缩略图
                            String thumbnailpath = ConstantUtil.FILE_PATH + rootpath + File.separator;
                            File newFile1 = new File(thumbnailpath);
                            if (!newFile1.exists()) {
                                newFile1.mkdirs();
                            }
                            // 生成缩略图
                            String truepath = VideoImageUtil.randomGrabberFFmpegImage(path, VideoImageUtil.MOD);
                            // 设置缩略图路径
                            materialFile.setThumbnailpath(truepath);
                        } else if (fileType.matches("^(.mp3|.MP3|.wav|.WAV)$")) {
                            // 音频文件默认缩略图
                            materialFile.setThumbnailpath(ConstantUtil.WEB_MP3FILE_PATH.substring(ConstantUtil.returnIp().length()));
                        } else {
                            // 其他文件默认缩略图
                            materialFile.setThumbnailpath(ConstantUtil.WEB_DEFAULTFILE_PATH.substring(ConstantUtil.returnIp().length()));
                        }
                        // 上传到xsky
                        // xskyService.uploadObject(ConstantUtil.XSKY_BUCKET_PHOTO, path, new
                        // File(path));

                        materialFileService.addFile(materialFile);// 添加文件信息
                        materialTypeDocumentService.updateDocAddCount(document);// 二级文件夹总数+1
                        data.put("value", materialFile);
                        result.setCode(ResultEnum.SUCCESS.getCode());
                        result.setMsg("上传成功！");
                        result.setData(data);
                    } else if (!StringUtil.isEmpty(fileString)) {// 解码Base64上传图片
                        String truefileType = fileString.substring(0, fileString.indexOf(":"));// 获取图片类型

                        String fileType = "." + truefileType;
                        // 自定义的文件名称
                        String trueFileName = String.valueOf(System.currentTimeMillis());
                        // 设置存放图片文件的路径
                        String filedocpath = ConstantUtil.FILE_PATH + rootpath + File.separator;
                        // 文件全路径
                        String truePath = filedocpath + trueFileName + fileType;

                        File newFile = new File(filedocpath);
                        if (!newFile.exists()) {
                            newFile.mkdirs();
                        }

                        // 对字节数组字符串进行Base64解码并生成图片
                        // Base64解码
                        BASE64Decoder decoder = new BASE64Decoder();
                        String base64String = fileString.substring(fileString.indexOf(":") + 1);// 去掉头部（不能解析）
                        log.info("Base64解码后:\n" + base64String);
                        byte[] b = decoder.decodeBuffer(base64String);
                        for (int i = 0; i < b.length; ++i) {
                            if (b[i] < 0) {// 调整异常数据
                                b[i] += 256;
                            }
                        }
                        // 生成jpeg图片
                        OutputStream out = new FileOutputStream(truePath);
                        out.write(b);
                        out.flush();
                        out.close();

                        MaterialFile materialFile = new MaterialFile();
                        materialFile.setId(StringUtil.generatorUUID());
                        materialFile.setMaterialtypedocumentid(documentid);
                        materialFile.setFilename(trueFileName);
                        materialFile.setUrl(truePath);
                        materialFile.setFiletype(fileType);
                        if (fileType.matches("^(.jpg|.png|.JPG|.PNG|.jpeg|.JPEG)$")) {// 如果文件后缀是图片格式就生成缩略图
                            String thumbnailpath = ConstantUtil.FILE_PATH + rootpath + File.separator;// 缩略图的存放位置
                            String thumbnailtruePath = thumbnailpath + trueFileName + "thumbnail" + ".jpg";
                            File newFile1 = new File(thumbnailpath);
                            if (!newFile1.exists()) {
                                newFile1.mkdirs();
                            }
                            // 生成缩略图
                            Thumbnails.of(truePath).size(200, 300).toFile(thumbnailtruePath);
                            // 设置缩略图路径
                            materialFile.setThumbnailpath(thumbnailtruePath);
                        }
                        materialFileService.addFile(materialFile);// 添加文件信息
                        materialTypeDocumentService.updateDocAddCount(document);// 二级文件夹总数+1
                        data.put("value", materialFile);
                        result.setCode(ResultEnum.SUCCESS.getCode());
                        result.setMsg("上传成功！");
                        result.setData(data);
                    } else {
                        data.put("value", "请选择文件上传！");
                        result.setCode(ResultEnum.FAIL.getCode());
                        result.setMsg("添加警告！");
                        result.setData(data);
                    }
                } catch (Exception e) {
                    log.info("addFile 异常:{}", e);
                    data.put("value", "系统异常，请稍后！");
                    result.setCode(ResultEnum.FAIL.getCode());
                    result.setMsg("添加异常！");
                    result.setData(data);
                }
            }
            return result;
        }
    }

    /**
     * 上传文件信息
     *
     * @param files      文件数组
     * @param documentId 文件夹id
     * @param fileString Base64格式字符串
     * @return
     */
/*    @MyPower(name = "上传卷宗文件", url = "/addFile2", isPublic = true)
    @RequestMapping(value = "/addFile2")
    public AppResult addFile2(@RequestParam(value = "file", required = false) MultipartFile[] files,
                              @NotNull(message = "传入的documentId为null，请传值")
                              @NotEmpty(message = "传入的documentId空字符串，请传值") String documentId, String fileString) {
        JSONObject data = new JSONObject();
        // 二级文件夹信息
        MaterialTypeDocument document = materialTypeDocumentService.findDocumentById(documentId);
        MaterialType mt;
        if (document == null) {
            data.put("value", "未查询到文件夹信息！");
            return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("添加警告！").setData(data);
        } else {
            // 一级目录信息
            mt = materialTypeService.findById(document.getMaterialtypeid());
        }

        if (materialFileService.addDossierFile(files, documentId, document, mt, fileString) > 0) {
            return AppResult.builder().setCode(ResultEnum.SUCCESS.getCode()).setMsg("文件上传成功！");
        } else {
            return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("文件上传失败！(可能原因：1.上传文件为空)");
        }

    }*/

    /**
     * 修改文件名称
     *
     * @param fileId      文件id
     * @param newFileName 新文件名称
     * @return
     */
    @MyPower(name = "修改文件名称", url = "/updateFileName", isPublic = true) // TODO
    @RequestMapping(value = "/updateFileName")
    public AppResult updateFileName(String fileId, String newFileName) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        if (StringUtil.isEmpty(newFileName)) {
            data.put("value", "请传入新的文件名！");
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("修改警告！");
            result.setData(data);
            return result;
        }
        int i = materialFileService.updateFileName(fileId, newFileName);
        if (i > 0) {
            data.put("value", i);
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("修改文件名称成功！");
            result.setData(data);
        } else {
            data.put("value", i);
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("修改文件名称失败！");
            result.setData(data);
        }
        return result;
    }

    /**
     * 批量删除文件根据文件id, 更新二级文件夹总数减1
     *
     * @param fileid     文件id(,分割 1,2,3)
     * @param documentid 上级文件夹id
     * @return
     */
    @MyPower(name = "批量删除文件", url = "/delFileById")
    @RequestMapping(value = "/delFileById")
    public AppResult delFileById(String fileid, String documentid) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        int i = materialFileService.delFileById(fileid, documentid);
        if (i == ResultEnum.FAIL.getCode()) {
            data.put("value", i);
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("请选择文件！");
            result.setData(data);
            return result;
        }
        data.put("value", i);
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setMsg("删除成功！");
        result.setData(data);
        return result;
    }

    /**
     * 新增二级文件夹 更新一级目录总数加1
     *
     * @param materialtypeid 一级目录id
     * @param documentname   文件夹名称
     * @return
     */
    @MyPower(name = "新增文件夹", url = "/addDocument")
    @RequestMapping(value = "/addDocument")
    public AppResult addDocument(@NotNull(message = "传入的materialtypeid为null，请传值")
                                 @NotEmpty(message = "传入的materialtypeid空字符串，请传值") String materialtypeid, @NotNull(message = "传入的documentname为null，请传值")
                                 @NotEmpty(message = "传入的documentname空字符串，请传值") String documentname) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        MaterialTypeDocument mtd = MaterialTypeDocument.builder().id(StringUtil.generatorUUID())
                .materialtypeid(materialtypeid).documentname(documentname).build();
        int i;
        if (ConstantUtil.XSKYRESTORAGE) {
            i = materialTypeDocumentService.addDocument2(mtd);
        } else {
            i = materialTypeDocumentService.addDocument(mtd);
        }

        if (i == ResultEnum.FAIL.getCode()) {
            data.put("value", mtd);
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("新建文件夹失败！");
            result.setData(data);
        } else if (i == -2) {
            data.put("value", mtd);
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("新建文件夹失败！(查询不到上级目录信息)");
            result.setData(data);
        } else {
            data.put("value", mtd);
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("新建文件夹成功！");
            result.setData(data);
        }
        return result;
    }

    /**
     * 新增二级文件夹 更新一级目录总数加1
     *
     * @param materialtypeid 一级目录id
     * @param documentname   文件夹名称
     * @return
     */
/*    @MyPower(name = "新增文件夹", url = "/addDocument2", isPublic = true)
    @RequestMapping(value = "/addDocument2")
    public AppResult addDocument2(@NotNull(message = "传入的materialtypeid为null，请传值")
                                  @NotEmpty(message = "传入的materialtypeid空字符串，请传值") String materialtypeid, @NotNull(message = "传入的documentname为null，请传值")
                                  @NotEmpty(message = "传入的documentname空字符串，请传值") String documentname) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        MaterialTypeDocument mtd = MaterialTypeDocument.builder().id(StringUtil.generatorUUID())
                .materialtypeid(materialtypeid).documentname(documentname).build();
        int i = materialTypeDocumentService.addDocument2(mtd);
        if (i == ResultEnum.FAIL.getCode()) {
            data.put("value", mtd);
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("新建文件夹失败！");
            result.setData(data);
        } else if (i == -2) {
            data.put("value", mtd);
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("新建文件夹失败！(查询不到上级目录信息)");
            result.setData(data);
        } else {
            data.put("value", mtd);
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("新建文件夹成功！");
            result.setData(data);
        }
        return result;
    }*/

    /**
     * 批量删除二级文件夹(更新状态为已删除) 更新一级目录总数减1
     *
     * @param documentid     文件夹id逗号分隔
     * @param materialtypeid 一级目录id
     * @return
     */
    @MyPower(name = "批量删除文件夹", url = "/delDocument")
    @RequestMapping(value = "/delDocument")
    public AppResult delDocument(String documentid, String materialtypeid) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        int i = materialTypeDocumentService.delDocument(documentid, materialtypeid);
        if (i == -2) {
            data.put("value", i);
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("该文件下还有文件！");
            result.setData(data);
        } else if (i == ResultEnum.FAIL.getCode()) {
            data.put("value", i);
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("请选择文件夹！");
            result.setData(data);
        } else {
            data.put("value", i);
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("删除文件夹成功！");
            result.setData(data);
        }
        return result;
    }

    /**
     * 根据案件编号与嫌疑人id查询卷宗目录（如果没有就新增卷宗一级目录）
     *
     * @param caseCode      警综案件编号
     * @param policeId      上传新增警员id
     * @param caseSuspectId 案件关联的嫌疑人id
     * @param isRetract     第几次撤回={0:未撤回;1:撤回第一次}(默认未撤回)
     * @return
     */
    @MyPower(name = "查询卷宗目录", url = "/findMeaterialModelBySusId")
    @RequestMapping(value = "/findMeaterialModelBySusId")
    public AppResult findMeaterialModelBySusId(@NotNull(message = "传入的caseCode为null，请传值")
                                               @NotEmpty(message = "传入的caseCode空字符串，请传值") String caseCode, String caseName,
                                               @NotNull(message = "传入的policeId为null，请传值")
                                               @NotEmpty(message = "传入的policeId空字符串，请传值") String policeId, @NotNull(message = "传入的caseSuspectId为null，请传值")
                                               @NotEmpty(message = "传入的caseSuspectId空字符串，请传值") String
                                                       caseSuspectId, @RequestParam(name = "isRetract", defaultValue = "0") int isRetract) {
        JSONObject data = new JSONObject();
        List<MaterialType> list;
        if (ConstantUtil.XSKYRESTORAGE) {
            list = materialTypeService.findMeaterialmodel2(caseCode, caseName, policeId, caseSuspectId,
                    isRetract);
        } else {
            list = materialTypeService.findMeaterialmodel(caseCode, caseName, policeId, caseSuspectId,
                    isRetract);
        }
        if (list == null) {
            return AppResult.builder().setCode(ResultEnum.FAIL.getCode()).setMsg("卷宗正在生成中，请稍后再试...");
        } else {
            data.put("value", list);
            return AppResult.builder().setCode(ResultEnum.SUCCESS.getCode()).setMsg(ResultEnum.SUCCESS.getMsg()).setData(data);
        }
    }

    /**
     * 查询卷宗目录
     *
     * @param caseCode      警综案件编号
     * @param policeId      上传新增警员id
     * @param caseSuspectId 案件关联的嫌疑人id
     * @param isRetract     第几次撤回={0:未撤回;1:撤回第一次}(默认未撤回)
     * @return
     */
/*    @MyPower(name = "查询卷宗目录", url = "/findMeaterialModelBySusId2", isPublic = true)
    @RequestMapping(value = "/findMeaterialModelBySusId2")
    public AppResult findMeaterialModelBySusId2(@NotNull(message = "传入的caseCode为null，请传值")
                                                @NotEmpty(message = "传入的caseCode空字符串，请传值") String caseCode, String caseName, @NotNull(message = "传入的policeId为null，请传值")
                                                @NotEmpty(message = "传入的policeId空字符串，请传值") String policeId, @NotNull(message = "传入的caseSuspectId为null，请传值")
                                                @NotEmpty(message = "传入的caseSuspectId空字符串，请传值") String
                                                        caseSuspectId, @RequestParam(name = "isRetract", defaultValue = "0") int isRetract) {
        JSONObject data = new JSONObject();
        data.put("value", materialTypeService.findMeaterialmodel2(caseCode, caseName, policeId, caseSuspectId,
                isRetract));
        return AppResult.builder().setCode(ResultEnum.SUCCESS.getCode()).setMsg("查询成功！").setData(data);
    }*/

    /**
     * 根据勾选的文件(或文件夹)进行压缩打包 TODO 存在bug,不同文件(或文件夹)但是是相同的名称则会一起打包
     *
     * @param casecode      警综案件编号
     * @param policeid      上传打包新增警员id
     * @param caseSuspectId 嫌疑人id
     * @param folderNames   打包(文件名)数组
     * @return
     */
    @MyPower(name = "根据勾选的文件进行压缩打包", url = "/fileZip")
    @RequestMapping(value = "/fileZip")
    public AppResult fileZip(String casecode, String caseSuspectId, String policeid,
                             @RequestParam(value = "folderNames[]") String[] folderNames) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("..........fileZip");
        MaterialPack mp = materialPackService.fileZip(casecode, caseSuspectId, policeid, folderNames);
        if (mp == null) {
            data.put("value", "失败原因可能：1.打包的文件不存在2.打包失败");
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("打包失败！");
            result.setData(data);
        } else {
            data.put("value", mp);
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("打包成功！");
            result.setData(data);
        }
        return result;
    }

    /**
     * 根据勾选的文件夹进行压缩打包
     *
     * @param materialTypeId 卷宗一级id(,分割)
     * @param documentId     文件夹id(,分割)
     * @return
     */
/*    @MyPower(name = "根据勾选的文件夹进行压缩打包", url = "/fileZipTwo", isPublic = true) // TODO
    @RequestMapping(value = "/fileZipTwo")
    public AppResult fileZipTwo(String materialTypeId, String documentId) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("..........fileZipTwo");
        MaterialPack mp = materialPackService.fileZipTwo(materialTypeId, documentId);
        if (mp == null) {
            data.put("value", "失败原因可能：1.打包的文件不存在2.打包失败");
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("打包失败！");
            result.setData(data);
        } else {
            data.put("value", mp);
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("打包成功！");
            result.setData(data);
        }
        return result;
    }*/

    /**
     * 根据勾选的文件夹进行压缩打包
     *
     * @param materialTypeId 卷宗一级id(,分割)
     * @param documentId     文件夹id(,分割)
     * @return
     */
    @MyPower(name = "根据勾选的文件夹进行压缩打包", url = "/fileZipTwo2", isPublic = true)
    @RequestMapping(value = "/fileZipTwo2")
    public AppResult fileZipTwo2(@RequestParam(name = "materialTypeId", required = false) String materialTypeId,
                                 @RequestParam(name = "documentId", required = false) String documentId) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        MaterialPack mp;
        if (ConstantUtil.XSKYRESTORAGE) {
            mp = materialPackService.fileZipTwo2(materialTypeId, documentId);
        } else {
            mp = materialPackService.fileZipTwo(materialTypeId, documentId);
        }
        if (mp == null) {
            data.put("value", "失败原因可能：1.打包的文件不存在2.打包失败");
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("打包失败！");
            result.setData(data);
        } else {
            data.put("value", mp);
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("打包成功！");
            result.setData(data);
        }
        return result;
    }

    /**
     * 打包列表结构 嫌疑人1 音频材料 执法音频 音频1 视频材料 执法视频1 执法视频2 嫌疑人2 音频材料 执法音频2 音频1 卷宗材料 侦查工作卷
     * 诉讼文书卷
     */
    /**
     * 查询打包记录列表
     *
     * @param pageNum
     * @param pageSize
     * @param policeId   警员id
     * @param keyWord    关键字
     * @param isDownload 是否下载{0：未下载1：已下载}
     * @return
     */
    @MyPower(name = "查询打包记录列表", url = "/findAllMaterialPackInfo")
    @RequestMapping(value = "/findAllMaterialPackInfo")
    public AppResult findAllMaterialPackInfo(@RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
                                             @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                             @RequestParam(name = "policeId") String policeId,
                                             @RequestParam(name = "keyWord", required = false) String keyWord,
                                             @RequestParam(name = "isDownload", required = false) String isDownload) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("..........findAllMaterialPackInfo:policeId=" + policeId);
        Page<MaterialPack> startPage = PageHelper.startPage(pageNum, pageSize);// 使用分页插件方法
        materialPackService.findAllMaterialPackInfo(policeId, keyWord, isDownload);

        MaterialPackVo mpv = materialPackService.findAllMaterialPackInfoCount(policeId);// 统计已下载，未下载数量

        data.put("value", startPage.getResult());
        data.put("total", startPage.getTotal());
        data.put("quantity", mpv);
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setMsg("查询成功！");
        result.setData(data);
        return result;
    }

    /**
     * 删除打包列表记录(更新状态为已删除)
     *
     * @param packid 打包列表id
     * @return
     */
    @MyPower(name = "删除打包列表记录(更新状态为已删除)", url = "/updateMateriaPack")
    @RequestMapping(value = "/updateMateriaPack")
    public AppResult updateMateriaPack(String packid) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("..........updateMateriaPack");
        int i = materialPackService.updateMateriaPack(packid);
        if (i == 0) {
            data.put("value", i);
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("删除失败！(请传入正确的id)");
            result.setData(data);
        } else {
            data.put("value", i);
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("删除成功！");
            result.setData(data);
        }
        return result;
    }

    /**
     * 加载打包的树 嫌疑人==>卷宗目录 加载打包的树
     *
     * @param casecode      警综案件编号
     * @param policeid      上传新增警员id
     * @param casesuspectid 案件关联的嫌疑人id
     * @return
     */
    @MyPower(name = "加载打包的列表", url = "/findMeaterialTree")
    @RequestMapping(value = "/findMeaterialTree")
    public AppResult findMeaterialTree(String caseCode, String caseName, String policeId, String caseSuspectId,
                                       @RequestParam(name = "isRetract", defaultValue = "0") int isRetract) {
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        log.info("..........findMeaterialTree");
        List<Node> list = materialTypeService.findMeaterialTree(caseCode, caseName, policeId, caseSuspectId, isRetract);

        data.put("value", list);
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setMsg("查询成功！");
        result.setData(data);
        return result;
    }

    /**
     * 下载打包文件
     *
     * @param packId 压缩文件的id
     * @return
     */
    @MyPower(name = "下载打包文件", url = "/downloadPack")
    @RequestMapping(value = "/downloadPack")
    public void downloadPack(String packId, HttpServletResponse response) {
        log.info("..........downloadPack");
        AppResult result = new AppResult();
        JSONObject data = new JSONObject();
        String url = materialPackService.findUrlById(packId);
        if (url == null) {
            data.put("value", "文件路径不存在！");
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("下载失败!");
            result.setData(data);
//			return result;
            log.info(data.toJSONString());
        }
        try {
            File file = new File(url);
            // 如果文件不存在，则显示下载失败
            if (!file.exists()) {
                data.put("value", "文件不存在！");
                result.setCode(ResultEnum.FAIL.getCode());
                result.setMsg("下载失败!");
                result.setData(data);
//				return result;
                log.info(data.toJSONString());
            } else {
                // 取得文件名。
                String fileName = file.getName();
                // 取得文件的后缀名。
//				String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();

                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(url));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                response.setHeader("Content-Type", "text/plain");
                // 解决IE和火狐浏览器不兼容，文件名有中文就乱码的问题
                fileName = URLEncoder.encode(fileName, "UTF-8");
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                response.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
//				response.setContentType("application/zip;charset=UTF-8");
////								// 设置要下载的文件的名称
//				response.setHeader("Content-Disposition",
//						"attachment;fileName=" + new String(fileName.getBytes(), "iso-8859ResultEnum.FAIL.getCode()"));
//
//				FileInputStream input = new FileInputStream(file);
//				OutputStream out = response.getOutputStream();
//				byte[] b = new byte[2048];
//				int len;
//				while ((len = input.read(b)) != ResultEnum.FAIL.getCode()) {
//					out.write(b, 0, len);
//				}
//				input.close();
//				out.close();
//				out.flush();
            }
        } catch (Exception e) {
            log.info("下载压缩文件失败:{}", e);
            data.put("value", e);
            result.setCode(ResultEnum.FAIL.getCode());
            result.setMsg("下载失败!");
            result.setData(data);
//			return result;
            log.info(data.toJSONString());
        }
        data.put("value", "下载压缩文件成功！");
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setMsg("下载成功!");
        result.setData(data);
//		return result;
        log.info(data.toJSONString());
    }

}
